<template>
  <div class="app-container dialog-w80">
    <div class="customContainer">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-date-picker
            v-model="pickerDate"
            value-format="yyyy.MM.dd"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select filterable placeholder="仓库" v-model="formInline.house_id">
            <el-option
              v-for="item in house_list"
              :key="item.house_id"
              :label="item.name"
              :value="item.house_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="订单状态:" v-model="formInline.status">
            <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formInline.order_no"
            placeholder="请输入采购单号"
            @keyup.enter.native="searchClick"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>

      <!-- 列表 -->
      <el-table
        highlight-current-row
        :data="list"
        v-loading.body="listLoading"
        border
        size="small"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="36"></el-table-column>
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">
            <span class="indexColor">{{scope.$index+1+(currentPage-1)*20}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status==0">待审核</span>
            <span v-if="scope.row.status==1">待确认</span>
            <span v-if="scope.row.status==2">待发货</span>
            <span v-if="scope.row.status==3">部分收货</span>
            <span v-if="scope.row.status==4">订单完结</span>
            <span v-if="scope.row.status==5">收货完成</span>
            <span v-if="scope.row.status==6">订单取消</span>
            <span v-if="scope.row.status==8">待收货</span>
            <span v-if="scope.row.status==9">申请退货中</span>
            <span v-if="scope.row.status==10">退货中</span>
            <span v-if="scope.row.status==11">退货完成</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单编号">
          <template slot-scope="scope">
            <el-button
              @click="get_order_info(scope.row.id,scope.$index,scope.row.status,scope.row.name,scope.row.order_id)"
              type="text"
              size="small"
            >{{scope.row.order_id}}</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="下单仓" prop="name"></el-table-column>
        <el-table-column align="center" label="下单时间" prop="creat_time"></el-table-column>
        <el-table-column align="center" label="到货差额	">
          <template slot-scope="scope">
            <!-- {{scope.row.total_gift*1>0?'-'+scope.row.total_gift:scope.row.total_gift}} -->
            {{scope.row.arrive_gift*1-scope.row.total_gift*1}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注">
          <template slot-scope="scope">
            <span class="indexColor">{{!scope.row.remark?'---':scope.row.remark}}</span>
          </template>
        </el-table-column>
        <!-- 列表的操作按钮 -->
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status==1||scope.row.status==2||scope.row.status==3||scope.row.status==8"
              @click="closeClick(scope.row.id,scope.$index,0)"
              type="danger"
              size="mini"
            >关闭订单</el-button>
            <el-button
              v-else-if="scope.row.status==9"
              @click="returnClick(scope.row.id,scope.$index,scope.row.status)"
              type="success"
              size="mini"
            >退货申请</el-button>
            <div v-else-if="scope.row.status==10">
              <div v-if="scope.row.type==1">
                <el-button
                  @click="returnClick(scope.row.id,scope.$index,scope.row.status)"
                  type="primary"
                  size="mini"
                >退货详情</el-button>
                <el-button
                  @click="returnOkClick(scope.row.id,scope.$index,scope.row.status)"
                  type="primary"
                  size="mini"
                >退货完成</el-button>
              </div>
              <el-button
                v-else
                @click="returnClick(scope.row.id,scope.$index,scope.row.status)"
                type="primary"
                size="mini"
              >退货详情</el-button>
            </div>
            <el-button
              v-else-if="scope.row.status==11"
              @click="returnClick(scope.row.id,scope.$index,scope.row.status)"
              type="primary"
              size="mini"
            >退货详情</el-button>
            <el-button v-else type="info" disabled size="mini">不可操作</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 弹框 -->
    <el-dialog
      :close-on-click-modal="false"
      class="dialog_table"
      title="采购单审核"
      :visible.sync="detail_dialog"
    >
      <div class="dialogInContainer" v-loading="dialogLoading">
        <span style="position:absolute;top:20px;left:180px">订单编号：{{order_id}}</span>
        <div style="position:relative;top:-20px">下单仓：{{name}}</div>
        <el-table
          highlight-current-row
          :data="infolist"
          v-loading.body="listLoading"
          border
          size="small"
        >
          <el-table-column align="center" label="序号" width="50">
            <template slot-scope="scope">
              <span class="indexColor">{{scope.$index+1}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="图片" width="70">
            <template slot-scope="scope">
              <img :src="scope.row.thumb" width="50" height="50" alt />
            </template>
          </el-table-column>
          <el-table-column align="center" label="礼品名称" prop="gift_name"></el-table-column>
          <el-table-column align="center" label="礼品编号" prop="gift_id"></el-table-column>
          <el-table-column align="center" label="箱规" prop="box_num"></el-table-column>
          <el-table-column align="center" label="尺寸">
            <template slot-scope="scope">
              <span>{{scope.row.size?scope.row.size:'-'}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="三级分类" prop="type_name"></el-table-column>
          <el-table-column align="center" label="采购单价" prop="money_sell"></el-table-column>
          <el-table-column align="center" label="发货">
            <template slot-scope="scope">
              <span>{{scope.row.supplier?scope.row.supplier:'未选择'}}</span>
              <!-- <el-button :disabled="scope.row.supplier==null" type="text" size="small">{{scope.row.supplier?scope.row.supplier:'未选择'}}</el-button> -->
            </template>
          </el-table-column>
          <el-table-column align="center" label="采购数" prop="total_num"></el-table-column>
          <el-table-column align="center" label="订单数" prop="order_num"></el-table-column>
          <el-table-column align="center" label="实际到货数" prop="arrive_num"></el-table-column>
          <el-table-column align="center" label="到货差异" prop="arrive_diff">
            <template slot-scope="scope">
              <span :class=" scope.row.arrive_diff==0?'':'danger'">{{scope.row.arrive_diff}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="备注">
            <template slot-scope="scope">
              <span class="danger" v-if="scope.row.is_insufficient==1">礼品库存不足</span>
              <span class="danger" v-if="scope.row.is_insufficient==2">礼品已下架</span>
              {{scope.row.remark_p}}
            </template>
          </el-table-column>
          <!-- 列表的操作按钮 -->
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-switch
                :disabled="isDisabled"
                active-value="0"
                inactive-value="1"
                v-model="scope.row.is_del"
              ></el-switch>
              <!-- <el-button @click="delClick(scope.row.gift_id,scope.$index,scope.row.is_on_sale)" type="danger" size="mini">关闭</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <!-- 自定义底部 -->
        <br />
        <div class="bottom_box">
          <el-button
            class="pull-right"
            :disabled="isDisabled"
            size="small"
            type="primary"
            @click="saveClick()"
          >确认提交</el-button>
          <p class="pull-right total_box">
            <span class="total">合计</span>
            <span>采购数：{{allTotal}}</span>
            <span>订单数：{{allOrder}}</span>
            <span>实际到货数：{{allArrive}}</span>
            <span>
              到货差异：
              <span :class="allArriveDiff==0?'':'danger'">{{allArriveDiff}}</span>
            </span>
          </p>
        </div>
      </div>
      <!-- </el-form> -->
    </el-dialog>

    <!-- 退货申请详情弹框 -->
    <el-dialog :close-on-click-modal="false" title="退货详情" :visible.sync="return_dialog">
      <el-table
        highlight-current-row
        :data="returnList"
        v-loading.body="listLoading"
        border
        fit
        size="small"
      >
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">
            <span class="indexColor">{{scope.$index+1}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单号" prop="order_id"></el-table-column>
        <el-table-column align="center" label="退货礼品名称" prop="name"></el-table-column>
        <el-table-column align="center" label="礼品编号" prop="gift_id"></el-table-column>
        <el-table-column align="center" label="退货礼品数量" prop="order_num"></el-table-column>
        <el-table-column align="center" label="退货礼品金额" prop="pay_money">
          <template slot-scope="scope">{{scope.row.order_num*scope.row.pay_money}}</template>
        </el-table-column>
        <el-table-column align="center" label="退货时间" prop="creat_time"></el-table-column>
        <el-table-column align="center" label="物流公司">
          <template
            slot-scope="scope"
          >{{scope.row.logistics_company==null?'-':scope.row.logistics_company}}</template>
        </el-table-column>
        <el-table-column align="center" label="物流单号">
          <template slot-scope="scope">{{scope.row.logistics_no==null?'-':scope.row.logistics_no}}</template>
        </el-table-column>
      </el-table>
      <!-- 自定义底部 -->
      <br />
      <div class="bottom_box">
        <el-form :inline="true" class="demo-form-inline pull-left" size="small">
          <el-form-item>
            <el-input v-model="return_remark" placeholder="备注信息"></el-input>
          </el-form-item>
        </el-form>
        <div class="pull-right" v-if="isShow">
          <el-button :disabled="isDisabled" size="small" type="primary" @click="if_return(1)">同意退货</el-button>
          <el-button :disabled="isDisabled" size="small" type="danger" @click="if_return(2)">拒绝退货</el-button>
        </div>
        <!-- <p class="pull-right" style="line-height:0">礼品总数量:{{totalOrder}} 　礼品总金额:{{totalPrice}} 　</p> -->
      </div>
      <!-- </el-form> -->
    </el-dialog>

    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination
        class="pull-left"
        background
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="20"
        layout="prev, pager, next, jumper"
        :total="totalDataNumber"
      ></el-pagination>
      <el-button
        :disabled="exportForm.length==0"
        class="pull-right"
        type="primary"
        size="small"
        @click="exportClick()"
        :loading="exportLoading"
      >
        调拨单导出
        <count-down ref="cd" />
      </el-button>
    </div>
  </div>
</template>
<script>
import {
  house,
  getList,
  getPage,
  order_info,
  save,
  close,
  getExport,
  getReturn,
  return_goods,
  return_order_ok,
} from "@/api/goodsflow/order_branch";
import {
  pickerOptionsSixMonth,
  pickerDateSixMonth,
  optionMaxTime198,
} from "@/utils";
export default {
  data() {
    return {
      exportLoading: false,
      dialogLoading: false,
      listLoading: false,
      name: "",
      order_id: "",
      status: [
        { id: -1, name: "全部" },
        { id: 1, name: "待确认" },
        { id: 2, name: "待发货" },
        { id: 3, name: "部分收货" },
        { id: 4, name: "订单完结" },
        { id: 5, name: "收货完成" },
        { id: 6, name: "订单取消" },
        { id: 8, name: "待收货" },
        { id: 9, name: "申请退货中" },
        { id: 10, name: "退货中" },
        { id: 11, name: "退货完成" },
      ],
      formInline: {
        house_id: 0,
        order_no: "",
        start: "",
        end: "",
        status: 1,
        position: "verify",
      },
      pickerOptions: pickerOptionsSixMonth(),
      pickerDate: pickerDateSixMonth(),
      house_list: [],
      list: null,
      totalDataNumber: 1,
      currentPage: 1,
      detail_dialog: false,
      return_dialog: false,
      infolist: [],
      returnList: [],
      switchVal: true,
      // totalOrder: "0",
      // totalPrice: "0",
      saveForm: {
        order_id: "",
        order_list: [],
      },
      editIndex: "",
      isDisabled: false,
      isShow: false,
      exportForm: [],
      exportData: [],
      return_remark: "",
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      if (!vm.list) {
        vm.gethouse();
        vm.searchClick();
      }
    });
  },
  methods: {
    gethouse() {
      house().then((response) => {
        this.house_list = response;
      });
    },
    searchClick() {
      optionMaxTime198(this.pickerDate).then(() => {
        //最大可选择时间区间
        this.formInline.start = this.pickerDate ? this.pickerDate[0] : "";
        this.formInline.end = this.pickerDate ? this.pickerDate[1] : "";
        this.fetchData();
      });
    },
    // 退货完成
    returnOkClick(id, index, status) {
      this.editIndex = index;
      this.$confirm("请确定礼品均已退回且数量正确", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        return_order_ok({ order_id: id }).then((response) => {
          this.$message({
            type: response.code == 1 ? "success" : "error",
            message: response.message,
          });
          if (response.code == 1) {
            this.list[this.editIndex].status = 11;
          }
        });
      });
    },
    // 关闭订单
    closeClick(id, index, status) {
      this.editIndex = index;
      this.$confirm("此操作为关闭, 是否继续?", "提示", {
        type: "warning",
      }).then(() => {
        close({ order_id: id, status: status }).then((response) => {
          this.$message({
            type: response.code == 1 ? "success" : "error",
            message: response.message,
          });
          if (response.code == 1) {
            this.list[this.editIndex].status = 6;
          }
        });
      });
    },
    // 提交
    saveClick() {
      const that = this;
      that.saveForm.order_list = [];
      this.infolist.forEach(function (val, index) {
        if (val.order_num == "" || val.order_num == 0) {
          return;
        } else {
          that.saveForm.order_list.push({
            look_money: val.money_sell,
            house_id: val.house_id,
            gift_id: val.gift_id,
            total_num: val.total_num,
            is_del: val.is_del,
            type: val.type,
            remark: val.remark ? val.remark : "",
            mapping_id: val.id,
            money_sell: val.money_sell,
            hosue_id: val.hosue_id,
          });
        }
      });
      if (this.saveForm.order_list.length == this.infolist.length) {
        this.$confirm("此操作提交, 是否继续?", "提示").then(() => {
          save(this.saveForm).then((response) => {
            this.$message({
              type: response.code == 1 ? "success" : "error",
              message: response.message,
            });
            if (response.code == 1) {
              this.list[this.editIndex].status = 1;
              this.detail_dialog = false;
              this.searchClick();
            }
          });
        });
      } else {
        that.$message({ type: "error", message: "请将所有信息填写完整!" });
        return;
      }
    },
    // 打开订单详情
    get_order_info(id, index, status, name, order_id) {
      this.dialogLoading = true;
      this.name = name;
      this.isDisabled = status == 1 ? false : true;
      this.editIndex = index;
      this.saveForm.order_id = id;
      this.order_id = order_id;
      this.detail_dialog = true;
      order_info(id).then((response) => {
        response.forEach((val) => {
          val.arrive_diff = val.arrive_num - val.order_num;
        });
        this.infolist = response;
        this.dialogLoading = false;
        // this.count();
      });
    },
    // 退货弹框
    returnClick(id, index, status) {
      this.isShow = status == 9 ? true : false;
      this.isDisabled = status == 9 ? false : true;
      this.editIndex = index;
      this.saveForm.order_id = id;
      this.return_dialog = true;
      getReturn(id).then((response) => {
        this.return_remark = response[0].remark;
        this.returnList = response;
        // this.count();
      });
    },
    // 退货按钮
    if_return(status) {
      return_goods({
        order_id: this.saveForm.order_id,
        status: status,
        remark: this.return_remark ? this.return_remark : "",
      }).then((response) => {
        this.$message({
          type: response.code == 1 ? "success" : "error",
          message: response.message,
        });
        if (response.code == 1) {
          this.list[this.editIndex].status = 10;
          this.return_dialog = false;
        }
      });
    },
    // 计算
    // count() {
    //     var totalPrice = 0; //临时总价
    //     var totalOrder = 0;
    //     this.infolist.forEach(function (val, index) {
    //         totalPrice += val.order_num * 1 * val.money_cost * 1; //累计总价
    //         totalOrder += val.order_num * 1;
    //     });
    //     this.totalPrice = parseFloat(totalPrice);
    //     this.totalOrder = parseFloat(totalOrder);
    // },
    // 选择
    handleSelectionChange(val) {
      this.exportForm = val;
    },
    // 导出按钮
    exportClick() {
      const idArr = [];
      this.exportForm.forEach(function (val, index) {
        idArr.push(val.id);
      });
      getExport({ order_id: idArr.join(",") }).then((response) => {
        this.exportData = response;
        this.export2Excel();
      });
      this.exportLoading = true;
      this.$refs.cd.countDownF(30).then(() => {
        this.exportLoading = false;
      });
    },
    // 导出
    export2Excel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require("../../vendor/Export2Excel");
        const tHeader = [
          "序号",
          "礼品名称",
          "礼品编号",
          "神采礼品编号",
          "礼品图片",
          "箱规",
          "一级分类",
          "二级分类",
          "三级分类",
          "系列",
          "材质",
          "订单数",
          "采购单号",
          "供应商",
          "收货仓",
          "收货地址",
          "联系人",
          "联系方式",
        ]; //对应表格输出的title
        const filterVal = [
          "ID",
          "gift_name",
          "id",
          "no_obsolete",
          "thumb",
          "box_num",
          "type_name_one",
          "type_name_second",
          "type_name",
          "serie_name",
          "texture",
          "order_num",
          "order_no",
          "supplier",
          "house_name_in",
          "address",
          "linkman",
          "phone",
        ]; // 对应表格输出的数据
        const list = this.exportData;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(
          tHeader,
          data,
          new Date(
            Date.UTC(
              new Date().getFullYear(),
              new Date().getMonth(),
              new Date().getDate()
            )
          )
            .toISOString()
            .slice(0, 10)
            .replace("-", "")
            .replace("-", "") + "采购单"
        ); //对应下载文件的名字
      });
    },
    // 导出
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      this.currentPage = 1;
      getPage(this.formInline)
        .then((response) => {
          this.totalDataNumber = response.page * 20;
          getList(this.formInline).then((response) => {
            this.list = response;
            this.listLoading = false;
          });
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    handleCurrentChange(val) {
      this.listLoading = true;
      getList(this.formInline, val).then((response) => {
        this.list = response;
        this.listLoading = false;
      });
    },
    //合计
    totalMethods(list, key) {
      return list.reduce(
        (prev, list) => prev + (list.is_del === "0" ? list[key] / 1 : 0),
        0
      );
    },
  },
  computed: {
    allTotal: function () {
      return this.totalMethods(this.infolist, "total_num");
    },
    allOrder: function () {
      return this.totalMethods(this.infolist, "order_num");
    },
    allArrive: function () {
      return this.totalMethods(this.infolist, "arrive_num");
    },
    allArriveDiff: function () {
      return this.totalMethods(this.infolist, "arrive_diff");
    },
  },
};
</script>


